package com.xgpro.common.websocket;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.response.OapiUserGetResponse;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @ClassName WebSocketInterceptor
 * @Author: LiKai
 * @Date: 2019-09-07 12:21
 * @Version 1.0
 * @Description
 */
public class WebSocketInterceptor implements HandshakeInterceptor {


    // 初次握手访问前
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {

        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            //获取域对象
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            //如果用户已登录，则将用户的信息放入域中，以便向特定的用户推送信息

            System.out.println("消息拦截器中的用户 id:"+session.getAttribute("id"));
            if (session.getAttribute("id") != null) {
                map.put("username", session.getAttribute("id"));//
                session.setAttribute("username",session.getAttribute("id"));
            }
        }
        return true;
    }

    // 初次握手访问后
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {

    }
}
